<template>
  <el-row>
    <el-col :span="10">
      <el-carousel trigger="click" height="300px" v-if="produceInfo.imgList.length > 0">
        <el-carousel-item v-for="item in produceInfo.imgList" :key="item">
          <el-image :src="item.url" fit="cover" style="height: 100%; min-width: 100%">
            <template #error>
              <div class="image-slot">
                <el-icon><picture /></el-icon>
              </div>
            </template>
          </el-image>
        </el-carousel-item>
      </el-carousel>
    </el-col>
    <el-col :span="14" class="header-right" >
      <el-descriptions
          :title="produceInfo.produceName"
          :column="1"
          size="large"
      >
        <el-descriptions-item label="上架日期：">{{produceInfo.collectionDate}}</el-descriptions-item>
        <el-descriptions-item label="来源农场：">{{produceInfo.merchantName}}</el-descriptions-item>
        <el-descriptions-item label="产品类别：">
          <el-tag :type="tag[produceInfo.produceType-1]">{{produceInfo.produceTypeName}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="产品售价：">￥&nbsp;{{ produceInfo.price }}</el-descriptions-item>
        <el-descriptions-item label="产品余量：">{{ produceInfo.count }}</el-descriptions-item>
        <el-descriptions-item label="产品简介：">{{ produceInfo.describe }}</el-descriptions-item>
      </el-descriptions>
      <br>
      <div v-if="isUser">
        <el-input-number v-model="buyCount" :precision="0" :step="1" :min="0" :max="produceInfo.count>buyCount?produceInfo.count:buyCount" style="margin-right: 40px" />
        <el-popover effect="light" trigger="hover" placement="top">
          <template #default>
            <div v-if="had">购物车中已存在该商品</div>
            <div v-else>添加产品到购物车中</div>
          </template>
          <template #reference>
            <el-button @click="addShopCar" :disabled="!buyCount>0" type="warning" round style="margin-right: 30px">{{(had?'覆盖':'加入')+'购物车'}}</el-button>
          </template>
        </el-popover>
        <el-button @click="selectAddress" :disabled="!buyCount>0" type="primary" round style="margin-right: 20px">购买</el-button>
      </div>
      <div v-else style="text-align: right">
        <span style="font-size: 18px; color: #ff6363">农场商家只能预览展示页面，无法购买农产品噢~</span>
      </div>
    </el-col>
  </el-row>
  <el-divider content-position="left">产品详细信息</el-divider>
  <el-collapse v-model="activeNames">
    <el-collapse-item title="萌芽期生长状况记录" name="1">
      <GrowthData growth-stage="0" :uuid="uuid"></GrowthData>
    </el-collapse-item>
    <el-collapse-item title="生长期生长状况记录" name="2">
      <GrowthData growth-stage="1" :uuid="uuid"></GrowthData>
    </el-collapse-item>
    <el-collapse-item title="成熟期生长状况记录" name="3">
      <GrowthData growth-stage="2" :uuid="uuid"></GrowthData>
    </el-collapse-item>
  </el-collapse>
  <SelectAddress :dialog-form-visible=dialogFormVisible @closeDialog="closeDialog" @commitBook="commitBook"></SelectAddress>
  <PayBook :dialog-form-visible=payBookDialogVisible :book-i-d="currentPayBook" @closeDialog="closePayBookDialog" @payCancel="payCancel" @paySuccess="paySuccess" ></PayBook>
</template>

<script>
import {ref, reactive, getCurrentInstance} from "vue";
import request from "@/http/request";
import GrowthData from "@/components/descriptions/GrowthData";
import SelectAddress from "@/components/dialog/SelectAddress";
import PayBook from "@/components/dialog/PayBook";
const {useRoute, useRouter} = require("vue-router");

export default {
  name: "FarmCropsDetails",
  components: {
    GrowthData,
    SelectAddress,
    PayBook,
  },
  data() {
    return {
      isUser: false,
      activeNames: ['1','2','3'],
      tag: ['success','danger','warning','info'],
      produceTypeList: [],
      produceInfo: reactive({
        collectionDate: "",
        produceName: "商品名称",
        produceType: 0,
        produceTypeName: "",
        merchantName: "",
        merchantID: "", // 农场id
        farmStatus: "", // 农场状态
        describe: "",
        price: 0,
        count: 0,
        imgList:[],
      }),
      had: false,
      buyCount: ref(0),
      dialogFormVisible: false,
      payBookDialogVisible: false,
      currentPayBook: "",
    }
  },
  methods: {
    getProduceType() {
      request({
        url: "/produce/getProduceType",
        method: "get",
      }).then((response) => {
        if (response.code === 200) {
          this.produceTypeList = response.data;
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    },
    getProduceDetail() {
      const _this = this;
      if (_this.uuid!=="") {
        request({
          "url": "produce/getProduceDetail",
          "method": "post",
          data: {
            uuid: _this.uuid,
          }
        }).then( (response)=> {
          if (response.code === 200) {
            _this.produceInfo.collectionDate = response.data[0].data.collectionDate;
            _this.produceInfo.merchantName = response.data[0].merchantName;
            _this.produceInfo.produceName = response.data[0].data.name;
            _this.produceInfo.produceType = response.data[0].data.produceType;
            _this.produceInfo.price = parseFloat(response.data[0].data.price).toFixed(2);
            _this.produceInfo.count = parseInt(response.data[0].data.count);
            _this.produceInfo.describe = response.data[0].data.describe;
            _this.produceInfo.imgList = response.data[0].imgList.map(function (item) {
              item.url = _this.staticResourcesUrl + item.img;
              return item;
            });
            this.getProduceTypeName();
          } else {
            _this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    getProduceTypeName() {
      this.produceTypeList.map((item)=>{
        if (item.code === this.produceInfo.produceType) {
          this.produceInfo.produceTypeName = item.name;
        }
      })
    },
    getUser() {
      this.isUser = localStorage.getItem("identityCode") === '1';
    },
    getShopCar() {
      this.$store.state.BookList.map((item)=>{
        if (item.uuid === this.uuid) {
          this.buyCount = Number(item.count);
          this.had = true;
        }
      })
    },
    addShopCar() {
      this.$store.commit("addBookItem", {data:{uuid: this.uuid, count: this.buyCount}, had: this.had});
      this.$tipUtil.successTip(this.produceInfo.produceName+'（数量：'+this.buyCount+'）已经在购物车等您啦~');
      this.getShopCar();
    },
    selectAddress() {
      this.dialogFormVisible = true;
    },
    closeDialog() {
      this.dialogFormVisible = false;
    },
    closePayBookDialog() {
      this.payBookDialogVisible = false;
    },
    commitBook(addressID) {
      if (addressID == null || addressID === '') {
        this.$tipUtil.errTip("您还未选择收货地址");
      } else {
        request({
          url: "/book/submitBook",
          method: "post",
          data:{
            list: [{uuid: this.uuid, count: this.buyCount}],
            addressID: addressID,
          }
        }).then((response) => {
          if (response.code === 200) {
            this.$tipUtil.successTip(response.msg);
            this.currentPayBook = response.data.bookID;
            this.payBookDialogVisible = true;
          } else {
            this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    payCancel() {
      this.$tipUtil.successTip("订单已提交，请您尽快支付噢~");
      this.$router.push({
        path: '/book/bookList',
        query: {
          state: '1',
        }
      })
    },
    paySuccess() {
      this.$router.push({
        path: '/book/bookList',
        query: {
          state: '2',
        }
      })
    },
  },
  setup() {
    const { appContext : { config: { globalProperties } } } = getCurrentInstance();
    const staticResourcesUrl = globalProperties.$staticResourcesUrl;
    const route = useRoute();
    const router = useRouter();
    const uuid = route.params.uuid;
    const scoreValue = ['优秀', '良好', '一般', '不足'];
    const PHValue = ['碱性', '弱碱性','中性','弱酸性','酸性'];
    const pesticideDoseValue = ['无农药喷洒', '低于正常值', '正常值', '高于正常值'];
    return {
      staticResourcesUrl,
      uuid,
      route,
      router,
      scoreValue,
      PHValue,
      pesticideDoseValue,
    }
  },
  mounted() {
    if (!this.uuid) {
      this.$tipUtil.warningTip("未获取到农产品id，为您跳转至主页！");
      this.router.replace({
        path: '/',
      });
    } else {
      this.getProduceType();
      this.getProduceDetail();
      this.getUser();
      this.getShopCar();
    }
  }
}
</script>

<style scoped>
.farmCropsDetails {
  height: 86vh;
  margin: 0;
  padding: 0;
}
.el-row {
  padding: 20px 0;
}
.header-right {
  padding: 0 20px;
  box-sizing: border-box;
  text-align: right;
}
</style>